import OpenFileDialog from '@/components/OpenFileDialog';
import { ITarget, IWork } from '@/ts/core';
import { RightOutlined } from '@ant-design/icons';
import { Button, Card, List, message } from 'antd';
import React, { useEffect, useState } from 'react';

interface IProps {
  target: ITarget;
}
const orderHandler: React.FC<IProps> = ({ target }) => {
  const [curItem, setCurItem] = useState<any>({});
  const [info, setInfo] = useState<any>(null);
  const [orderList, setOrderList] = useState([
    { id: 1, key: 'seller', title: '原单位订单处理', bindInfo: {} },
    { id: 2, key: 'buyer', title: '申请单位订单处理', bindInfo: {} },
  ]);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    getTargetCache();
  }, []);

  const getTargetCache = async () => {
    const result: any = await target.cacheObj.get('orderProcessingTasks');
    if (result && Object.keys(result || {}).length > 0) {
      setInfo(result);
      setOrderList((prevList: any[] = []) =>
        prevList.map((item) => {
          if ('seller_order_task' in result && item.key === 'seller') {
            return {
              ...item,
              bindInfo: {
                work: result['seller_order_task'],
              },
            };
          }
          if ('buyer_order_task' in result && item.key === 'buyer') {
            return {
              ...item,
              bindInfo: {
                work: result['buyer_order_task'],
              },
            };
          }
          return item;
        }),
      );
    }
  };

  const onListItemClick = async (item: any) => {
    setCurItem(item);
    setVisible(true);
  };

  const handleUpdateOrderConfig = async (work: IWork) => {
    const res = await target.cacheObj.set('orderProcessingTasks', {
      ...(info || {}),
      [`${curItem.key}_order_task`]: work.metadata,
    });

    if (res) {
      message.info('保存成功');
      target.updateMetadata({
        ...target.metadata,
        [`${curItem.key}_order_task`]: work.metadata,
      });
      // 更新对象中的某个属性
      setOrderList((prevList: any[] = []) =>
        prevList.map((item) => {
          if (item.key === curItem.key) {
            return {
              ...item,
              bindInfo: {
                work: work.metadata,
              },
            };
          }
          return item;
        }),
      );
      setVisible(false);
    } else {
      message.warn('保存失败');
    }
  };

  const handleRemoveBinding = async () => {
    await target.cacheObj.set('orderProcessingTasks', undefined);
    setOrderList((prevList: any[] = []) =>
      prevList.map((item) => {
        return {
          ...item,
          bindInfo: {},
        };
      }),
    );
  };

  return (
    <>
      <Card
        title="订单处理"
        extra={
          info && (
            <Button type="primary" size="small" onClick={handleRemoveBinding}>
              解除绑定
            </Button>
          )
        }>
        <List
          className="demo-loadmore-list"
          itemLayout="horizontal"
          dataSource={orderList}
          renderItem={(item: any) => (
            <List.Item
              actions={[
                item.bindInfo?.work ? (
                  <span
                    key="list-loadmore-edit"
                    onClick={() => {
                      onListItemClick(item);
                    }}>
                    已绑定【{item.bindInfo?.work?.name}】<RightOutlined />
                  </span>
                ) : (
                  <a
                    key="list-loadmore-edit"
                    onClick={() => {
                      onListItemClick(item);
                    }}>
                    绑定 <RightOutlined />
                  </a>
                ),
              ]}>
              {item.title}
            </List.Item>
          )}
        />
      </Card>

      {visible && (
        <OpenFileDialog
          title={`选择办事（${curItem.title}）`}
          accepts={['办事']}
          rootKey={target.directory.spaceKey}
          allowInherited
          multiple={false}
          onOk={async (files) => {
            if (files.length > 0) {
              handleUpdateOrderConfig(files[0] as unknown as IWork);
            }
          }}
          onCancel={() => setVisible(false)}
        />
      )}
    </>
  );
};

export default orderHandler;
